﻿using Common;
using DevExpress.XtraEditors;
using DevExpress.XtraRichEdit;
using DLL;
using NursingFormSystem.BLL;
using NursingFormSystem.Common;
using NursingFormSystem.Model;
using SQLDLL;
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace NursingFormSystem.BloodGlucoseMonitoring
{
    public partial class BloodGlucEntryForm : XtraForm
    {
        public string DepartID;
        public string DepartName;
        public string Nursecellid;
        public string Nursecellname;
        public string NurseID;
        public string VISITID;
        public bool insert = true;
        public string Id;
        public string[] User;//操作用户
        public string[] Patient;//患者信息
        public Random rd = new Random();　　//无参即为使用系统时钟为种子
        public Tb_User LoginUser;
        public BloodGlucEntryForm(string[] user, string[] patient)
        {
            InitializeComponent();
            //构造参数赋值
            User = user;
            Patient = patient;
            VISITID = patient[1];
            DepartID = patient[8];
            DepartName = patient[9];
            Nursecellid = patient[10];
            Nursecellname = patient[11];
            NurseID = user[0];
            this.Id = string.Empty;

            //电签数据赋值
            InitLoginUser(user);

            //绑定数据
            txtE_Signature.Text = user[1];
            lab_Name.Text = patient[2];
            lab_BedNo.Text = patient[5];
            lab_PatientID.Text = patient[0];
            BindInfo(this.Id);
            ElectronicSignature();
        }
        public BloodGlucEntryForm(string[] user, string[] patient, string id)
        {
            InitializeComponent();
            //构造参数赋值
            User = user;
            Patient = patient;
            VISITID = patient[1];
            DepartID = patient[8];
            DepartName = patient[9];
            Nursecellid = patient[10];
            Nursecellname = patient[11];
            NurseID = user[0];
            this.Id = id;

            //电签数据赋值
            InitLoginUser(user);

            //绑定数据
            txtE_Signature.Text = user[1];
            lab_Name.Text = patient[2];
            lab_BedNo.Text = patient[5];
            lab_PatientID.Text = patient[0];
            BindInfo(this.Id);
            ElectronicSignature();
        }
        public Tb_User InitLoginUser(string[] UserParam)
        {
            LoginUser = new Tb_User();
            LoginUser.UserId = UserParam[0];
            LoginUser.UserName = UserParam[1];
            LoginUser.DepartmentCode = UserParam[2];
            LoginUser.DepartmentName = UserParam[3];
            LoginUser.JobTitle = UserParam[4];
            LoginUser.PositionTitle = UserParam[5];
            return LoginUser;
        }
        /// <summary>
        /// 初始化加载印章图片
        /// </summary>
        private void ElectronicSignature()
        {
            ElectronicSignature es = new ElectronicSignature(LoginUser);
            es.SearchElectronicSignatureImage(Base.ESSwitch, LoginUser, txtE_Signature, picElectronicSignature, txtE_Signature.Location);
        }

        private void BindInfo(string id)
        {
            if (string.IsNullOrEmpty(id) || id == "-1")  //新增
            {
                InitializationControlsData(groupControl1.Controls);
                insert = true;
            }
            else  //修改
            {
                insert = false;
                this.Text = "血糖单修改";
                string Select = string.Format(@"SELECT * FROM [BNNursingDocsSystem_Develop].[dbo].[t_Bloodsugar](NOLOCK) where Id = '{0}'", id);
                DataSet Temp = SqlHelper.ExecuteDataset(Select, System.Data.CommandType.Text);
                DataTable nursedata = Temp.Tables[0];
                if (nursedata.Rows.Count > 0)
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    StringReader Nurseingdata = new StringReader(nursedata.Rows[0]["data"].ToString());
                    xmlDoc.Load(Nurseingdata);
                    XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
                    textMorning.Text = nursingrecord.ChildNodes[0].InnerText;
                    txtBF1.Text = nursingrecord.ChildNodes[1].InnerText;
                    txtBF2.Text = nursingrecord.ChildNodes[2].InnerText;
                    textLC1.Text = nursingrecord.ChildNodes[3].InnerText;
                    textLC2.Text = nursingrecord.ChildNodes[4].InnerText;
                    this.txtDN1.Text = nursingrecord.ChildNodes[5].InnerText;
                    txtDN2.Text = nursingrecord.ChildNodes[6].InnerText;
                    txtBeforeSleep.Text = nursingrecord.ChildNodes[7].InnerText;
                    txtOther1.Text = DateTimeHelper.HHmmssToHHmm(nursingrecord.ChildNodes[8].InnerText);
                    txtOther2.Text = nursingrecord.ChildNodes[9].InnerText;
                    txtOther3.Text = DateTimeHelper.HHmmssToHHmm(nursingrecord.ChildNodes[10].InnerText);
                    txtOther4.Text = nursingrecord.ChildNodes[11].InnerText;
                    txtOther5.Text = DateTimeHelper.HHmmssToHHmm(nursingrecord.ChildNodes[12].InnerText);
                    txtOther6.Text = nursingrecord.ChildNodes[13].InnerText;
                    txtOther7.Text = DateTimeHelper.HHmmssToHHmm(nursingrecord.ChildNodes[14].InnerText);
                    txtOther8.Text = nursingrecord.ChildNodes[15].InnerText;
                    txtbloodt1.Text = DateTimeHelper.HHmmssToHHmm(nursingrecord.ChildNodes[16].InnerText);
                    txtbloodt2.Text = nursingrecord.ChildNodes[17].InnerText;
                    txtbloodt3.Text = DateTimeHelper.HHmmssToHHmm(nursingrecord.ChildNodes[18].InnerText);
                    txtbloodt4.Text = nursingrecord.ChildNodes[19].InnerText;
                    object objdate = nursedata.Rows[0]["Date"];
                    if (objdate != null && !string.IsNullOrEmpty(objdate.ToString()))
                        dateE_Date.Text = objdate.ToString();
                    else
                        dateE_Date.DateTime = DateTime.Now;
                    txtSyncSN.Text = nursedata.Rows[0]["syncSN"].ToString();
                    txtUpdateuserId.Text = nursedata.Rows[0]["UpdateuserId"].ToString();
                }
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Empty_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 初始化控件数据数据
        /// </summary>
        private void InitializationControlsData(Control.ControlCollection Controls)
        {
            string sign = txtE_Signature.Text;
            foreach (var control in Controls)
            {
                if (control.GetType().Name == "ComboBoxEdit")
                {
                    ((ComboBoxEdit)control).EditValue = "请选择";
                }
                else if (control.GetType().Name == "CheckEdit")
                {
                    ((CheckEdit)control).Checked = false;
                }
                else if (control.GetType().Name == "TextEdit")
                {
                    ((TextEdit)control).Text = "";
                }
                else if (control.GetType().Name == "DateEdit")
                {
                    ((DateEdit)control).DateTime = System.DateTime.Now;
                }
                else if (control.GetType().Name == "TimeEdit")
                {
                    ((TimeEdit)control).Text = System.DateTime.Now.ToString("HH:mm");
                }
                else if (control.GetType().Name == "RichEditControl")
                {
                    ((RichEditControl)control).Text = "";
                }
                else if (control.GetType().Name == "DateTimePicker")
                {
                    ((DateTimePicker)control).Text = "00:00";
                }
            }
            txtE_Signature.Text = sign;
        }

        bool checkinput()
        {
            if (txtBeforeSleep.Text.Length > 0)
            {
                if (Convert.ToDouble(txtBeforeSleep.Text) < 32 || Convert.ToDouble(txtBeforeSleep.Text) > 43)
                {
                    XtraMessageBox.Show("体温输入错误");
                    return false;
                }
            }

            if (txtbloodt4.Text.Length > 0)
            {
                if (Convert.ToDouble(txtbloodt4.Text) < 0 || Convert.ToDouble(txtbloodt4.Text) > 150)
                {
                    XtraMessageBox.Show("呼吸输入错误");
                    return false;
                }
            }

            if (txtBF1.Text.Length > 0)
            {
                if (Convert.ToDouble(txtBF1.Text) < 0 || Convert.ToDouble(txtBF1.Text) > 300)
                {
                    XtraMessageBox.Show("高压输入错误");
                    return false;
                }
            }

            if (txtBF2.Text.Length > 0)
            {
                if (Convert.ToDouble(txtBF2.Text) < 0 || Convert.ToDouble(txtBF2.Text) > 300)
                {
                    XtraMessageBox.Show("低压输入错误");
                    return false;
                }
            }
            return true;
        }
        private void btn_Submit_Click(object sender, EventArgs e)
        {
            if (!ValidateTime()) return;
            string data = @"<?xml version=";
            data += @"""";
            data += "1.0";
            data += @"""";
            data += @"?> <BloodSugarRecordDocument> 
                  <WeeHour>" + textMorning.Text + @"</WeeHour>  
                  <breadfastbefore>" + this.txtBF1.Text + @"</breadfastbefore>  
                  <breadfastafter>" + txtBF2.Text + @"</breadfastafter>  
                  <lunchbefore>" + this.textLC1.Text + @"</lunchbefore>  
                  <lunchafter>" + textLC2.Text + @"</lunchafter>  
                  <dinnerbefore>" + this.txtDN1.Text + @"</dinnerbefore>  
                  <dinnerafter>" + txtDN2.Text + @"</dinnerafter>  
                  <bedtime>" + this.txtBeforeSleep.Text + @"</bedtime>  
                  <sugartime1>" + this.txtOther1.Text + @"</sugartime1>  
                  <sugar1>" + txtOther2.Text + @"</sugar1>  
                  <sugartime2>" + txtOther3.Text + @"</sugartime2>  
                  <sugar2>" + txtOther4.Text + @"</sugar2>  
                  <sugartime3>" + txtOther5.Text + @"</sugartime3>  
                  <sugar3>" + txtOther6.Text + @"</sugar3>  
                  <sugartime4>" + txtOther7.Text + @"</sugartime4>  
                  <sugar4>" + txtOther8.Text + @"</sugar4>  
                  <ketonetime1>" + this.txtbloodt1.Text + @"</ketonetime1>  
                  <ketone1>" + txtbloodt2.Text + @"</ketone1>  
                  <ketonetime2>" + txtbloodt3.Text + @"</ketonetime2>  
                  <ketone2>" + txtbloodt4.Text + @"</ketone2> 
                </BloodSugarRecordDocument>";
            SynchroBLL synchro = new SynchroBLL();
            ClinicalNursinguser cn = new ClinicalNursinguser();

            if (insert)  //插入模式
            {
                string existsSql = "if(EXISTS(SELECT TOP 1 Id FROM dbo.t_Bloodsugar(NOLOCK) WHERE [Date] = '{0}' AND PatientId='{1}' AND VISIT_ID='{2}')) SELECT 1 ELSE SELECT 0";
                existsSql = string.Format(existsSql, dateE_Date.DateTime.ToString("yyyy-MM-dd"), lab_PatientID.Text, VISITID);
                object exist = SqlHelper.ExecuteScalar(CommandType.Text, existsSql);//1 存在 0不存在
                if (exist.ToString().Equals("1")) { XtraMessageBox.Show("当前日期已经有血糖单"); return; }

                string rst = System.DateTime.Now.ToString("yyyyMMddHHmmss") + rd.Next(100, 10000).ToString();//用rad生成大于等于1000，小于等于9999的随机数
                string TempInsert = @"insert into [BNNursingDocsSystem_Develop].[dbo].[t_Bloodsugar]  ([PatientId]
                                          ,[VISIT_ID]
                                          ,[PatientName]
                                          ,[DepId]
                                          ,[DepName]
                                          ,[AreaId]
                                          ,[AreaName]
                                          ,[Date]
                                          ,[Time]
                                          ,[data]
                                          ,[Submittime]
                                          ,[SubmituserId]
                                          ,[SubmituserName]
                                          ,[Updatetime]
                                          ,[UpdateuserId]
                                          ,[UpdateuserName]
                                          ,[syncSN]) VALUES(
                                         '" + lab_PatientID.Text + @"','"
                                              + VISITID + @"',
                                          '" + lab_Name.Text + @"',
                                          '" + DepartID + @"',
                                          '" + DepartName + @"',
                                          '" + Nursecellid + @"',
                                          '" + Nursecellname + @"',  
                                          '" + dateE_Date.DateTime.ToString("yyyy-MM-dd") + @"',
                                         '',
                                          '" + data + @"',
                                          '" + System.DateTime.Now.ToString() + @"',
                                         '" + NurseID + @"',
                                         '" + txtE_Signature.Text + @"',
                                         '" + System.DateTime.Now.ToString() + @"',
                                         '" + NurseID + @"',
                                         '" + txtE_Signature.Text + @"',
                                         '" + rst + @"'                                        
                                         )";
                int num = SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, TempInsert);
                if (num > 0)
                {
                    XtraMessageBox.Show("新增成功");
                    #region 上传海泰
                    if (Base.ESSwitchHT == "1")
                    {
                        cn.PatientId = lab_PatientID.Text;
                        cn.PatientName = lab_Name.Text;
                        cn.DepId = DepartID;
                        cn.DepName = DepartName;
                        cn.AreaId = DepartID;
                        cn.AreaName = DepartName;
                        cn.data = data;
                        cn.Date = dateE_Date.DateTime.ToString("yyyy-MM-dd");
                        cn.Time = System.DateTime.Now.ToString("HH:mm:ss");
                        cn.NursName = txtE_Signature.Text;
                        cn.VisitId = Convert.ToInt32(VISITID);
                        cn.syncSN = rst;
                        cn.Updatetime = System.DateTime.Now;
                        cn.UpdateuserName = txtSyncSN.Text;
                        cn.UpdateuserId = NurseID;
                        synchro.bloodsugarInfoAsyncToEMRDelegateMethod(cn, "1");
                    }
                    #endregion
                    this.Close();
                }
                else
                {
                    XtraMessageBox.Show("新增失败");
                }
            }
            else //修改模式
            {
                string update = @"use BNNursingDocsSystem_Develop ; update [BNNursingDocsSystem_Develop].[dbo].[t_Bloodsugar] set 
                  [Date] = '" + dateE_Date.DateTime.ToString("yyyy-MM-dd") + @"'
                 ,[Data] = '" + data + @"'
                ,[Updatetime] = '" + System.DateTime.Now.ToString() + @"'
                ,[UpdateuserId] = '" + NurseID + @"'
                ,[UpdateuserName] = '" + txtE_Signature.Text + @"'
                  WHERE Id='" + Id + "'";
                int num = SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, update);
                if (num > 0)
                {
                    XtraMessageBox.Show("修改成功");
                    #region 上传海泰
                    if (Base.ESSwitchHT == "1")
                    {
                        cn.PatientId = lab_PatientID.Text;
                        cn.PatientName = lab_Name.Text;
                        cn.DepId = DepartID;
                        cn.DepName = DepartName;
                        cn.AreaId = DepartID;
                        cn.AreaName = DepartName;
                        cn.data = data;
                        cn.Date = dateE_Date.DateTime.ToString("yyyy-MM-dd");
                        cn.Time = dateE_Date.DateTime.ToString("yyyy-MM-dd");
                        cn.Updatetime = System.DateTime.Now;
                        cn.UpdateuserId = NurseID;
                        cn.UpdateuserName = txtE_Signature.Text;
                        cn.VisitId = Convert.ToInt32(VISITID);
                        cn.NursName = txtE_Signature.Text;
                        cn.syncSN = txtSyncSN.Text;
                        cn.UpdateuserId = txtUpdateuserId.Text;
                        cn.UpdateuserName = txtE_Signature.Text;
                        synchro.bloodsugarInfoAsyncToEMRDelegateMethod(cn, "2");
                    }
                    #endregion
                    this.Close();
                }
                else
                {
                    XtraMessageBox.Show("修改失败");
                }
            }

            //电签开始
            if (Base.ESSwitch.Equals("on"))
            {
                string signXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><huanzhehao name=\"患者号\">" + lab_PatientID.Text + "</huanzhehao><xingming name=\"姓名\">" + lab_Name.Text + "</xingming>"
                   + "<chuanghao name=\"床号\">" + lab_BedNo.Text + "</chuanghao><riqi name=\"日期\">" + dateE_Date.DateTime.ToString("yyyy-MM-dd") + "</riqi><lingchensnashi Name=\"凌晨3时\">" + textMorning.Text + "</lingchensnashi>"
                   + "<zaocan Name=\"早餐\">" + txtBF1.Text + "</zaocan><zaocan Name=\"早餐\">" + txtBF2.Text + "</zaocan><wucan Name=\"午餐\">" + textLC1.Text + "</wucan><wucan Name=\"午餐\">" + textLC2.Text + "</wucan>"
                   + "<wancan Name=\"晚餐\">" + txtDN1.Text + "</wancan><wancan Name=\"晚餐\">" + txtDN2.Text + "</wancan><shuiqian Name=\"睡前\">" + txtBeforeSleep.Text + "</shuiqian>"
                   + "<shijian Name=\"时间\">" + txtOther1.Text + "</shijian><xuetang Name=\"血糖\">" + txtOther2.Text + "</xuetang><shijian Name=\"时间\">" + txtOther3.Text + "</shijian><xuetang Name=\"血糖\">" + txtOther4.Text + "</xuetang>"
                   + "<shijian Name=\"时间\">" + txtOther5.Text + "</shijian><xuetang Name=\"血糖\">" + txtOther6.Text + "</xuetang><shijian Name=\"时间\">" + txtOther7.Text + "</shijian><xuetang Name=\"血糖\">" + txtOther8.Text + "</xuetang>"
                   + "<shijian Name=\"时间\">" + txtbloodt1.Text + "</shijian><xuetong Name=\"血酮\">" + txtbloodt2.Text + "</xuetong><shijian Name=\"时间\">" + txtbloodt3.Text + "</shijian><xuetong Name=\"血酮\">" + txtbloodt4.Text + "</xuetong>"
                   + "<qianming Name=\"签名\">" + txtE_Signature.Text + "</qianming>";
                //TODO:电签接口提交
                string extraInfo = "<?xml version=\"1.0\" encoding=\"UTF-16\"?><root><sign_sys>{0}</sign_sys><title>{1}</title><patient_id>{2}</patient_id><patient_name>{3}</patient_name><emr_id>{4}</emr_id><emr_catalog>{5}</emr_catalog><his_id>{6}</his_id><event_no>{7}</event_no><visit_number>{8}</visit_number><dept_name>{9}</dept_name><prescribe_number>{10}</prescribe_number><prescribe_sub_number>{11}</prescribe_sub_number><prescribe_operation>医嘱操作（发送、校对、停止、作废）或门诊处方操作（发送）</prescribe_operation><radiotherapy_id>放疗号</radiotherapy_id><process_name>CT定位申请单审核</process_name><process_time>CT定位申请单审核时间</process_time><extend_value_1>备用扩展1</extend_value_1><extend_value_2>备用扩展2</extend_value_2><extend_value_3>备用扩展3</extend_value_3><extend_value_4>备用扩展4</extend_value_4><extend_value_5>备用扩展5</extend_value_5><extend_value_6>备用扩展6</extend_value_6><extend_value_7>备用扩展7</extend_value_7><extend_value_8>备用扩展8</extend_value_8><extend_value_9>备用扩展9</extend_value_9></root>";
                extraInfo = string.Format(extraInfo, EnumHelper.GetDescription(FormType.Bloodsugar) + (this.Id.Equals("-1") ? "-新增" : "-更新"), EnumHelper.GetDescription(FormType.Bloodsugar), Patient[0], Patient[2], this.Id, (int)FormType.Bloodsugar, "", Patient[0], Patient[1], LoginUser.DepartmentName, Patient[0], Patient[0]);
                ElectronicSignature es = new ElectronicSignature(LoginUser);
                bool res = es.GetElectronicSignatureImage(es, signXml, extraInfo, ((int)FormType.Bloodsugar).ToString(), EnumHelper.GetDescription(FormType.Bloodsugar), Patient[0], Convert.ToInt32(Patient[1]));
                if (!res) { MessageBox.Show("电子签名失败"); return; }
            }//电签结束
        }
        private bool ValidateTime()
        {
            txtbloodt1.Text = DateTimeTran.TimeFillZero(txtbloodt1.Text);
            txtbloodt3.Text = DateTimeTran.TimeFillZero(txtbloodt3.Text);
            txtOther1.Text = DateTimeTran.TimeFillZero(txtOther1.Text);
            txtOther3.Text = DateTimeTran.TimeFillZero(txtOther3.Text);
            txtOther5.Text = DateTimeTran.TimeFillZero(txtOther5.Text);
            txtOther7.Text = DateTimeTran.TimeFillZero(txtOther7.Text);
            if ((!string.IsNullOrEmpty(txtOther1.Text) && string.IsNullOrEmpty(txtOther2.Text)) || (string.IsNullOrEmpty(txtOther1.Text) && !string.IsNullOrEmpty(txtOther2.Text)))
            {
                MessageBox.Show("时间和血糖要一起补全");
                return false;
            }
            if ((!string.IsNullOrEmpty(txtOther3.Text) && string.IsNullOrEmpty(txtOther4.Text)) || (string.IsNullOrEmpty(txtOther3.Text) && !string.IsNullOrEmpty(txtOther4.Text)))
            {
                MessageBox.Show("时间和血糖要一起补全");
                return false;
            }
            if ((!string.IsNullOrEmpty(txtOther5.Text) && string.IsNullOrEmpty(txtOther6.Text)) || (string.IsNullOrEmpty(txtOther5.Text) && !string.IsNullOrEmpty(txtOther6.Text)))
            {
                MessageBox.Show("时间和血糖要一起补全");
                return false;
            }
            if ((!string.IsNullOrEmpty(txtOther7.Text) && string.IsNullOrEmpty(txtOther8.Text)) || (string.IsNullOrEmpty(txtOther7.Text) && !string.IsNullOrEmpty(txtOther8.Text)))
            {
                MessageBox.Show("时间和血糖要一起补全");
                return false;
            }
            if ((!string.IsNullOrEmpty(txtbloodt1.Text) && string.IsNullOrEmpty(txtbloodt2.Text)) || (string.IsNullOrEmpty(txtbloodt1.Text) && !string.IsNullOrEmpty(txtbloodt2.Text)))
            {
                MessageBox.Show("时间和血酮要一起补全");
                return false;
            }
            if ((!string.IsNullOrEmpty(txtbloodt3.Text) && string.IsNullOrEmpty(txtbloodt4.Text)) || (string.IsNullOrEmpty(txtbloodt3.Text) && !string.IsNullOrEmpty(txtbloodt4.Text)))
            {
                MessageBox.Show("时间和血酮要一起补全");
                return false;
            }
            return true;

        }
        private void txtOther1_DoubleClick(object sender, EventArgs e)
        {
            txtOther1.Text = System.DateTime.Now.ToString("HH:mm");
        }
        private void txtOther3_DoubleClick(object sender, EventArgs e)
        {
            txtOther3.Text = System.DateTime.Now.ToString("HH:mm");
        }
        private void txtOther5_DoubleClick(object sender, EventArgs e)
        {
            txtOther5.Text = System.DateTime.Now.ToString("HH:mm");
        }
        private void txtOther7_DoubleClick(object sender, EventArgs e)
        {
            txtOther7.Text = System.DateTime.Now.ToString("HH:mm");
        }
        private void txtbloodt1_DoubleClick(object sender, EventArgs e)
        {
            txtbloodt1.Text = System.DateTime.Now.ToString("HH:mm");
        }
        private void txtbloodt3_DoubleClick(object sender, EventArgs e)
        {
            txtbloodt3.Text = System.DateTime.Now.ToString("HH:mm");
        }
        /// <summary>
        /// 设置 enter键当做Tab切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TemperatureEdit1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SendKeys.SendWait("{Tab}");
            }
        }
    }
}
